package com.cruise.game.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cruise.game.model.entity.Chat;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 聊天Mapper
 *
 * @author cruise
 * @date 2025-02-28
 */
public interface ChatMapper extends BaseMapper<Chat> {

    /**
     * 分页查询用户聊天记录
     *
     * @param page 分页对象
     * @param userId 用户ID
     * @return 分页聊天记录
     */
    @Select("SELECT * FROM chats WHERE user_id = #{userId} ORDER BY created_at DESC")
    IPage<Chat> selectUserChatHistory(Page<Chat> page, @Param("userId") Long userId);

    /**
     * 分页查询用户与管理员的聊天记录
     *
     * @param page 分页对象
     * @param userId 用户ID
     * @param adminId 管理员ID
     * @return 分页聊天记录
     */
    @Select("SELECT * FROM chats WHERE user_id = #{userId} AND admin_id = #{adminId} ORDER BY created_at DESC")
    IPage<Chat> selectUserAdminChatHistory(Page<Chat> page, @Param("userId") Long userId, @Param("adminId") Long adminId);

    /**
     * 查询指定时间后的聊天记录
     *
     * @param userId 用户ID
     * @param adminId 管理员ID
     * @param afterTime 时间点
     * @return 聊天记录列表
     */
    @Select("SELECT * FROM chats WHERE user_id = #{userId} AND admin_id = #{adminId} AND created_at > #{afterTime} ORDER BY created_at ASC")
    List<Chat> selectChatAfterTime(@Param("userId") Long userId, @Param("adminId") Long adminId, @Param("afterTime") LocalDateTime afterTime);

    /**
     * 获取用户未读消息数
     *
     * @param userId 用户ID
     * @param lastReadTime 最后读取时间
     * @return 未读消息数
     */
    @Select("SELECT COUNT(*) FROM chats WHERE user_id = #{userId} AND is_from_user = 0 AND created_at > #{lastReadTime}")
    int countUnreadMessages(@Param("userId") Long userId, @Param("lastReadTime") LocalDateTime lastReadTime);
}